﻿using System;
using System.IO;
using System.Xml;
using ECM7.NantContrib.Types;
using Microsoft.Web.Publishing.Tasks;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Tasks.Xml
{
	/// <summary>
	/// Таск для трансформации XML документов при помощи XDT
	/// <para>
	/// Синтаксис файлов трансформации см. <see cref="http://msdn.microsoft.com/ru-ru/library/dd465326.aspx"/>
	/// </para>
	/// </summary>
	[TaskName("xdt")]
	public class XdtTask : BaseTask
	{
		[BuildElement("transformation", Required = true)]
		public RawXmlData Transformation { get; set; }

		[TaskAttribute("target", Required = true)]
		public FileInfo Target { get; set; }

		protected override void ExecuteTask()
		{
			XmlTransformation tr = GetTransformation();

			Log(Level.Info, "Transform file '{0}'", Target.FullName);
			XmlDocument document = new XmlDocument();
			document.Load(Target.FullName);

			tr.Apply(document);
			document.Save(Target.FullName);

			Log(Level.Info, "Transformation completed");
		}

		private XmlTransformation GetTransformation()
		{
			if (Transformation.File != null)
			{
				if (!Transformation.File.Exists)
				{
					throw new BuildException("Transformation file should be exist", Location);
				}

				Log(Level.Info, "Using transformation file '{0}'", Transformation.File.FullName);
				return new XmlTransformation(Transformation.File.FullName, true, null);
			}

			var xml = Transformation.GetXml();

			if (xml == null)
			{
				throw new BuildException("Transformation is not specified", Location);
			}

			Log(Level.Info, "Using transformation xml from task");
			return new XmlTransformation(xml.OuterXml, false, null);
		}
	}
}
